package com.querycenter.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.opensymphony.xwork2.ModelDriven;
import com.querycenter.model.UserInfo;
import com.querycenter.serviceinter.UserManageServiceInter;

public class UserManageAction implements ModelDriven<UserInfo> {

	private UserManageServiceInter userManageService = null;
	private UserInfo userInfo = new UserInfo();
	String flagName = "_";

	// 查询用户的基本信息
	public String selectUserAllInfo() {

		try {
			// 添加用户
			System.out.println("name=" + userInfo.getUsername());
			if (userInfo.getUsername() != null
					&& !userInfo.getUsername().equals("")
					&& !userInfo.getUsername().equals(flagName)
					&& userInfo.getId() == 0) {
				userInfo.setLv(1);
				userInfo.setPw("000000");
				userManageService.insertUser(userInfo);
				flagName = userInfo.getUsername();
				userInfo.setUsername("");
			}
			// 修改用户
			if (userInfo.getId() != 0) {
				userManageService.updateUser(userInfo);
				userInfo.setId(0);
				userInfo.setUsername("");
			}

			HttpServletRequest request = ServletActionContext.getRequest();

			String pageNumberS = request.getParameter("num");// 输入跳转页数
			String curr = request.getParameter("page");// 上下以及末页数

			int pageSize = 10;// 当前页面数据大小
			int pageNumber = 1;// 初始化当前页数
			if (pageNumberS == "" || pageNumberS == null) {
				pageNumber = 1;
			} else {
				pageNumber = Integer.parseInt(pageNumberS);
			}
			// 查询总条数
			int pageCount = userManageService.selectCount();

			int i = (pageCount + pageSize - 1) / pageSize;// 最大页
			request.setAttribute("pageCount", i);
			if (curr != null && Integer.parseInt(curr) > 0
					&& (Integer.parseInt(curr) <= i + 1) && (pageNumber == 1)) {
				pageNumber = Integer.parseInt(curr);
			}
			if (i < pageNumber) {
				pageNumber = i;
			}

			// 获取用户的个人信息
			PageList<UserInfo> list1 = userManageService
					.selectUserAllInfo(pageNumber, pageSize);

			int currentPage = 1;

			request.setAttribute("list", list1);
			currentPage = pageNumber;

			request.setAttribute("currentPage", currentPage);

		} catch (Exception e) {

		}
		return "success";
	}

	// 关闭用户
	public void deleteUser() {

		HttpServletRequest request = ServletActionContext.getRequest();

		String id = request.getParameter("id");

		userManageService.deleteUser(Integer.parseInt(id));
		userInfo.setId(0);
		userInfo.setUsername("");
	}

	public UserManageServiceInter getUserManageService() {
		return userManageService;
	}

	public void setUserManageService(UserManageServiceInter userManageService) {
		this.userManageService = userManageService;
	}

	public UserInfo getUser() {
		return userInfo;
	}

	public void setUser(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	@Override
	public UserInfo getModel() {
		return userInfo;
	}

}
